//
//  PlanRecommendView.m
//  WanCaiC8
//
//  Created by tangang on 2018/3/23.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "PlanRecommendView.h"
#import "PlanRecommendCell.h"
#import "PlanRecommendTopCell.h"
#import "PlanRecommendHeadView.h"
#import "PlanVM.h"
#import "InformationVM.h"
#import "MJRefresh.h"
#import "AdvertisingView.h"
#import "TGAdvertTableViewCell.h"
#import "AdvertisingTableViewCell.h"
@interface PlanRecommendView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) PlanRecommendHeadView *headView;
@property (nonatomic ,strong) UICollectionView *numCollectionView;
@property (nonatomic ,strong) UICollectionView *typeCollectionView;
@property (nonatomic ,strong) NSMutableArray   *dataArr;
@property (nonatomic ,strong) NSMutableArray   *advertisingArr;
@property (nonatomic ,assign) NSInteger page;


@property (nonatomic ,strong) NSMutableArray   *arr1;
@property (nonatomic ,strong) NSMutableArray   *arr2;
@property (nonatomic ,strong) NSMutableArray   *arr3;
@property (nonatomic ,strong) NSMutableArray   *colArr1;
@property (nonatomic ,strong) NSMutableArray   *colArr2;
@property (nonatomic ,strong) NSMutableArray   *colArr3;

//@property(nonatomic,copy)NSString lookNewStr;

@end

@implementation PlanRecommendView{
    LotteryNumType numType;
    dispatch_source_t _timer;
}


#pragma mark - 启动定时器
- (void)startTimer{
    
    WS(weakSelf);
    
    [self cancleTimer];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),20.0*NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(_timer, ^{

        weakSelf.page=1;
        [weakSelf loadData];
        
    });
    
    
    
    dispatch_resume(_timer);
}


- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    if (self=[super initWithFrame:frame style:UITableViewStylePlain]) {
        
        self.advertisingArr =[NSMutableArray array];
        self.pageSize = 10;
        self.delegate=self;
        self.dataSource=self;
        self.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self registerClass:[PlanRecommendTopCell class] forCellReuseIdentifier:@"PlanRecommendTopCell"];
      
        [self registerClass:[PlanRecommendCell class] forCellReuseIdentifier:@"PlanRecommendCell"];
        
        self.rowHeight=UITableViewAutomaticDimension;
        self.estimatedRowHeight=40;
        
        WS(weakSelf);
        self.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf setPage:1];
//            page=1;
//            [weakSelf.dataArr removeAllObjects];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf reloadData];
//
//            });
            [weakSelf loadData];
        }];
        self.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//            [weakSelf loadData];
            [self loadMoreData];
        }];

        
        [self getAdvertising];
        
        [self startTimer];
    }
    return self;
}

- (void)setLotteryModel:(LotteryTypeModel *)lotteryModel{
    _lotteryModel=lotteryModel;
    numType=[[BaseVM manage] getType:[self.lotteryModel.lType integerValue]];
    [self.headView cancleTimer];
    [self.headView removeFromSuperview];
    self.headView=nil;
    self.tableHeaderView=self.headView;

    [self.header beginRefreshing];
}

//- (void)setPageSize:(NSInteger)pageSize{
//    _pageSize=pageSize;
//    self.page=1;
//    [self.header beginRefreshing];
//
//}

//- (void)setIsNew:(BOOL)isNew{
//    _isNew=isNew;
//    self.headView.isNew=isNew;
//    if (isNew) {
//        self.dataArr=[[NSMutableArray alloc]initWithObjects:self.recommendModel, nil];
//        self.headView.frame=CGRectMake(0, 0, SCREEN_WIDTH, real_size(75));
//        [self reloadData];
//
//    }else{
//        self.headView.frame=CGRectMake(0, 0, SCREEN_WIDTH, real_size(115));
//        [self.header beginRefreshing];
//    }
//    self.tableHeaderView=self.headView;
//    [self reloadData];
//    [self getAdvertising];
//}

#pragma mark -- 获取广告
- (void)getAdvertising{
    WS(weakSelf);
   
//    if ([BaseVM manage].city.length>0) {
        [[InformationVM manage] getAdvertWithLocation:@"0" andType:10 Success:^(id returnValue) {
            weakSelf.advertisingArr=returnValue;
           
            [self addAdvertisin];

            
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
//    }
}

- (void)addAdvertisin{
//    AdvertisingModel *adModel=nil;
//    for (AdvertisingModel *model in self.advertisingArr) {
//        if (model.Layer==1) {
//            adModel=model;
//            break;
//        }
//    }
//    if (adModel) {
//        self.headView.frame=CGRectMake(0, 0, SCREEN_WIDTH, real_size(115));
//        [self.headView setAdvertisingModel:adModel];
//    }
//    self.tableHeaderView=self.headView;
    
   
    self.arr1 = [NSMutableArray array];
    self.arr2 = [NSMutableArray array];
    self.arr3 = [NSMutableArray array];
    self.colArr1 = [NSMutableArray array];
    self.colArr2 = [NSMutableArray array];
    self.colArr3 = [NSMutableArray array];
    
    for (AdvertisingModel *model in self.advertisingArr) {
        if (model.Layer==1) {
            [self.arr1 addObject:model];
            if (model.IsDisplay) {
                [self.colArr1 addObject:model];
            }
        }else if (model.Layer==2){
            [self.arr2 addObject:model];
            if (model.IsDisplay) {
                [self.colArr2 addObject:model];
            }
        }else if(model.Layer == 3){
            
            [self.arr3 addObject:model];
            if (model.IsDisplay) {
                [self.colArr3 addObject:model];
            }
        
        }
    }
    
    

    [self reloadData];

}

- (void)onclickAd:(UITapGestureRecognizer *)tap{
    AdvertisingModel *adModel=nil;
    for (AdvertisingModel *model in self.advertisingArr) {
        if (model.Layer==tap.view.tag) {
            adModel=model;
            break;
        }
    }
    

    if ([adModel.Title containsString:@"】"]) {
        
        UIPasteboard *copy = [UIPasteboard generalPasteboard];
        NSRange startRange = [adModel.Title rangeOfString:@"【"];
        NSRange endRange = [adModel.Title rangeOfString:@"】"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        NSString *result = [adModel.Title substringWithRange:range];
        
        [copy setString:result];
        
        [SVProgressHUD showSuccessWithStatus:@"复制成功"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
        });

    }else{
        if (adModel.TransferUrl.length<1) {
            return;
        }
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString: adModel.TransferUrl]];
        
    }
}

-(void)loadMoreData{
    WS(weakSelf);

    [[PlanVM manage] getPlanDataWithLtype:[self.lotteryModel.lType integerValue] andPageIndex:weakSelf.page andPageSize:self.pageSize Success:^(id returnValue) {
        
                weakSelf.page+=1;
        
                NSArray *arr=returnValue;
                if (arr.count<weakSelf.pageSize) {
                    [weakSelf.footer noticeNoMoreData];
                }else{
                    [weakSelf.footer endRefreshing];
                }
                [weakSelf createData:returnValue];
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [weakSelf reloadData];
//
//                });
            } andFail:^(NSString *errorMessage, NSError *error) {

                [weakSelf.footer endRefreshing];
            }];
    
}

- (void)loadData{
    WS(weakSelf);
//    [[PlanVM manage] getPlanDataWithLtype:[self.lotteryModel.lType integerValue] andPageIndex:weakSelf.page andPageSize:self.pageSize Success:^(id returnValue) {
//        [weakSelf.header endRefreshing];
//
//
//        NSArray *arr=returnValue;
//        if (arr.count<weakSelf.pageSize) {
//            [weakSelf.footer noticeNoMoreData];
//        }else{
//            [weakSelf.footer endRefreshing];
//        }
//        [weakSelf createData:returnValue];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf reloadData];
//
//        });
//    } andFail:^(NSString *errorMessage, NSError *error) {
//        [weakSelf.header endRefreshing];
//        [weakSelf.footer endRefreshing];
//    }];
    
    
    
    if (self.lotteryModel.lType ==nil) {
        return;
    }
    [[BaseVM manage] GET_Field_Url:@"api/Plan/GetPlanData" Params:@{@"lType":@([self.lotteryModel.lType integerValue]),@"pageIndex":@(weakSelf.page),@"pageSize":@(self.pageSize)} successBlock:^(id returnValue) {
        
        [weakSelf.header endRefreshing];
        weakSelf.page+=1;

        if ([[returnValue objectForKey:@"Code"] intValue]==APIResponseStutusSuccess) {
            
            NSArray *arr=[PlanRecommendModel mj_objectArrayWithKeyValuesArray:[[returnValue objectForKey:@"Data"] objectForKey:@"PageData"]];
            
            
            if (arr.count<weakSelf.pageSize) {
                [weakSelf.footer noticeNoMoreData];
            }else{
                [weakSelf.footer endRefreshing];
            }
            
            if (arr.count>0) {
                [self.dataArr removeAllObjects];
                [weakSelf createData:arr];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if ([returnValue objectForKey:@"ExtraData"]!=nil) {
                    [weakSelf.headView.lookNew setTitle:[NSString stringWithFormat:@"查看%@期%@计划",[returnValue objectForKey:@"ExtraData"],self.lotteryModel.lType] forState:UIControlStateNormal];
                }
                
            });
            
            
        }else{
            [SVProgressHUD showErrorWithStatus:[returnValue objectForKey:@"Desc"]];
//            fail(nil,nil);
        }
        
    } failBlock:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD showErrorWithStatus:errorMessage];
//        fail(nil,nil);
        
        [weakSelf.header endRefreshing];
        [weakSelf.footer endRefreshing];
    }];
     

}

- (void)cancleTimer{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
    [self.headView cancleTimer];
    
}

- (void)createData:(NSArray *)arr{
    
    for (PlanRecommendModel *model in arr) {
        if ([model.ShowSort isEqualToString:@"龙虎"]) {
            continue;
        }
        ///六彩
        if ([[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeLottery) {
            if ([model.ShowSort isEqualToString:@"特尾大小"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"特尾大小"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"特合单双"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"四肖中特"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"十码中特"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"六不中"]) {
                continue;
            }
        }
        ///双色球
        if ([[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeChromosphere) {
            if ([model.ShowSort isEqualToString:@"红2胆"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"蓝5码"]) {
                continue;
            }
        }
        ///福彩3D和排三
        if ([[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeLottery3D||[[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeArrangement3) {
            if ([model.ShowSort isEqualToString:@"杀一码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"杀二码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"胆一码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"胆二码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"胆三码"]) {
                continue;
            }
        }
        
        
        if (model.OpenNum.length>0) {
            BOOL isHave =NO;
            for (RecommendModel *rModel in self.dataArr) {
                if ([rModel.Issue isEqualToString:model.Issue]) {
                    isHave=YES;
                    [rModel.arr addObject:model];
                    break;
                }
            }
            if (!isHave) {
                RecommendModel *rModel=[[RecommendModel alloc]init];
                rModel.OpenTime=model.OpenTime;
                rModel.Issue=model.Issue;
                rModel.OpenNum=model.OpenNum;
                rModel.OpenNumAlias=model.OpenNumAlias;
                rModel.lType=model.lType;
                [rModel.arr addObject:model];
                [self.dataArr addObject:rModel];
            }
        }
     
    }
    WS(weakSelf);
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf reloadData];

    });
    
}


#pragma mark -- UITableViewDelegate ,UITableViewDataSource
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//
//}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArr.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    RecommendModel *rModel=self.dataArr[section];
    if (section == 0) {
        return rModel.arr.count+1+(self.arr1.count?1:0);

    }else if (section == 1){
        return rModel.arr.count+1+(self.arr2.count?1:0);

    }else if (section==2){
        return rModel.arr.count+1+(self.arr3.count?1:0);
    }else{
        return rModel.arr.count+1;

    }
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    view.backgroundColor=DEFAULTBGCOLOR;
    return view;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecommendModel *rModel=self.dataArr[indexPath.section];
    if (indexPath.row==0) {
        PlanRecommendTopCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PlanRecommendTopCell" forIndexPath:indexPath];
        PlanRecommendModel *model=rModel.arr.lastObject;
        cell.count=[model.Num componentsSeparatedByString:@"|"].count+1.0;
        cell.model=rModel;
//        cell.isNew=self.isNew;
        return cell;
    }else{
        
        if (indexPath.row-1<rModel.arr.count) {
            PlanRecommendCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PlanRecommendCell" forIndexPath:indexPath];
            cell.row=indexPath.row-1;
            cell.model=rModel.arr[indexPath.row-1];
            //    cell.isNew=self.isNew;
            if (indexPath.row%2==0) {
                [cell setBgColor:[UIColor whiteColor]];
            }else{
                [cell setBgColor:DEFAULTBGCOLOR];
            }
            return cell;
        }else{
  
                if (indexPath.section == 0) {
                    [tableView registerClass:[TGAdvertTableViewCell class] forCellReuseIdentifier:@"TGAdvertTableViewCell1"];
                    TGAdvertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TGAdvertTableViewCell1" forIndexPath:indexPath];
                    [cell setAdModelArr:self.arr1 AndRowCount:(NSInteger)(self.arr1.count-ceil(self.colArr1.count/2.0))];
                    return cell;
            }else if (indexPath.section == 1){
                [tableView registerClass:[TGAdvertTableViewCell class] forCellReuseIdentifier:@"TGAdvertTableViewCell2"];
                TGAdvertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TGAdvertTableViewCell2" forIndexPath:indexPath];
                
                [cell setAdModelArr:self.arr2 AndRowCount:(NSInteger)(self.arr2.count-ceil(self.colArr2.count/2.0))];

                return cell;
            }else{
                [tableView registerClass:[TGAdvertTableViewCell class] forCellReuseIdentifier:@"TGAdvertTableViewCell3"];
                TGAdvertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TGAdvertTableViewCell3" forIndexPath:indexPath];
                [cell setAdModelArr:self.arr3 AndRowCount:(NSInteger)(self.arr3.count-ceil(self.colArr3.count/2.0))];
                return cell;
            }

        }
        
    }

    
    
}
- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr =[[NSMutableArray alloc]init];
    }
    return _dataArr;
}

- (PlanRecommendHeadView *)headView{
    if (!_headView) {
        _headView=[[PlanRecommendHeadView alloc] initWithType:numType];
        _headView.lType=self.lotteryModel.lType;
        _headView.lookNewBlock = self.lookeMore;
    }
    return _headView;
}



-(void)dealloc{
    
    NSLog(@"planRecommendView--->dealloc");
    
}
@end
